package wqh.controller.json;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import wqh.domain.*;
import wqh.pojo.IPConver;
import wqh.pojo.MapRet;
import wqh.pojo.MonitorExport;
import wqh.service.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by devts on 2016/11/1.
 */
@Controller
@CrossOrigin(origins = "*")
@RequestMapping("/export")
public class ExportJSON {

    private Logger logger = LoggerFactory.getLogger(ExportJSON.class);

    @Autowired
    private AlarmConfirmService alarmConfirmService;

    @Autowired
    private GeoBuildingService geoBuildingService;

    @Autowired
    private MonitorService monitorService;

    @Autowired
    private SensorService sensorService;

    @Autowired
    private DeviceService deviceService;

    @ResponseBody
    @RequestMapping(value = "/alarm",method = RequestMethod.GET)
    public Object alarm(HttpServletResponse response, @RequestParam(value = "start",required = true) int start,
                                        @RequestParam(value = "end",required = true) int end)
    {
        try{
            List<AlarmConfirm> alarmConfirmList = alarmConfirmService.findExportLog(start,end);
            if(alarmConfirmList.size() == 0) return MapRet.FILE_DOWNLOAD_ERROR();
            HSSFWorkbook book = new HSSFWorkbook();
            HSSFSheet sheet = book.createSheet();
            String[] columns = {"报警时间","区域","建筑物","楼层","报警主机","传感器类别","报警点名称","报警点回路号","报警类别","确认状态","确认时间"};
            HSSFRow headRow = sheet.createRow(0);
            for(int i = 0; i < columns.length; i++){
                HSSFCell cell = headRow.createCell(i);
                cell.setCellValue(columns[i]);
                sheet.setColumnWidth(i,38*150);
            }
            for(int i = 1; i < alarmConfirmList.size() +1; i++){
                AlarmConfirm a = alarmConfirmList.get(i-1);
                HSSFRow nextRow = sheet.createRow(i);
                HSSFCell cell = nextRow.createCell(0);
                cell.setCellValue(new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new java.util.Date(Long.parseLong(a.getAlarm_time().toString()) * 1000)));
                cell = nextRow.createCell(1);
                cell.setCellValue(a.getGeo_1_name());
                cell = nextRow.createCell(2);
                cell.setCellValue(a.getGeo_2_name());
                cell = nextRow.createCell(3);
                cell.setCellValue(a.getGeo_3_name());
                cell = nextRow.createCell(4);
                cell.setCellValue(a.getDevice_name());
                cell = nextRow.createCell(5);
                cell.setCellValue(a.getSensor_name());
                cell = nextRow.createCell(6);
                cell.setCellValue(a.getMonitor_name());
                cell = nextRow.createCell(7);
                cell.setCellValue(a.getDev_addr());
                cell = nextRow.createCell(8);
                cell.setCellValue(a.getDev_status());
                cell = nextRow.createCell(9);
                if(a.getConfirm_status() == 1) cell.setCellValue("确认");
                if(a.getConfirm_status() == 2) cell.setCellValue("忽略");
                if(a.getConfirm_status() == 3) cell.setCellValue("误报");
                cell = nextRow.createCell(10);
                cell.setCellValue(new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new java.util.Date(Long.parseLong(a.getConfirm_time().toString()) * 1000)));
            }
            String fileName = "报警记录.xls";
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            book.write(os);
            byte[] content = os.toByteArray();
            InputStream is = new ByteArrayInputStream(content);
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName).getBytes(), "iso-8859-1"));
            ServletOutputStream out = response.getOutputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(out);
            byte[] buff = new byte[4096];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bis.close();
            bos.close();
            return MapRet.FILE_DOWNLOAD_SUCCESS();
        }catch (Exception e){
            e.printStackTrace();
            logger.error("报警记录导出错误：" + e);
            return MapRet.FILE_DOWNLOAD_ERROR();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/device",method = RequestMethod.GET)
    public Object device(HttpServletResponse response)
    {
        try{
            List<Device> deviceList = deviceService.findAllRecord();
            if(deviceList.size() == 0) MapRet.FILE_DOWNLOAD_ERROR();
            HSSFWorkbook book = new HSSFWorkbook();
            HSSFSheet sheet = book.createSheet();
            String[] columns = {"报警主机","主机IP","主机备注"};
            HSSFRow headRow = sheet.createRow(0);
            for(int i = 0; i < columns.length; i++){
                HSSFCell cell = headRow.createCell(i);
                cell.setCellValue(columns[i]);
                sheet.setColumnWidth(i,38*150);
            }
            for(int i = 1; i < deviceList.size() +1; i++){
                Device a = deviceList.get(i-1);
                HSSFRow nextRow = sheet.createRow(i);
                HSSFCell cell = nextRow.createCell(0);
                cell.setCellValue(a.getName());
                cell = nextRow.createCell(1);
                cell.setCellValue(IPConver.int2Ip(a.getIp()));
                cell = nextRow.createCell(2);
                cell.setCellValue(a.getDescription());
            }
            String fileName = "用户信息传输装置记录.xls";
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            book.write(os);
            byte[] content = os.toByteArray();
            InputStream is = new ByteArrayInputStream(content);
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName).getBytes(), "iso-8859-1"));
            ServletOutputStream out = response.getOutputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(out);
            byte[] buff = new byte[4096];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bis.close();
            bos.close();
            return MapRet.FILE_DOWNLOAD_SUCCESS();
        }catch (Exception e){
            e.printStackTrace();
            logger.error("用户信息传输装置导出错误：" + e);
            return MapRet.FILE_DOWNLOAD_ERROR();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/monitor",method = RequestMethod.GET)
    public Object monitor(HttpServletResponse response)
    {
        try {
            List<GeoBuilding> geoBuildingList = geoBuildingService.findAllRecord();
            if(geoBuildingList.size() == 0) return MapRet.FILE_DOWNLOAD_ERROR();
            List<Device> deviceList = deviceService.findAllRecord();
            if(deviceList.size() == 0) return MapRet.FILE_DOWNLOAD_ERROR();
            List<Sensor> sensorList = sensorService.findAllRecord();
            if(sensorList.size() == 0) return MapRet.FILE_DOWNLOAD_ERROR();
            List<Monitor> monitorList = monitorService.findAllRecord();
            if(monitorList.size() == 0) return MapRet.FILE_DOWNLOAD_ERROR();
            List<MonitorExport> monitorExportList = new ArrayList<MonitorExport>();
            for(Monitor monitor : monitorList){
                MonitorExport monitorExport = new MonitorExport();
                monitorExport.setArea(getGeobuildingName(monitor.getGeo_level_1_id(),geoBuildingList));
                monitorExport.setBuilding(getGeobuildingName(monitor.getGeo_level_2_id(),geoBuildingList));
                monitorExport.setFloor(getGeobuildingName(monitor.getGeo_level_3_id(),geoBuildingList));
                monitorExport.setDevice_name(getDeviceName(monitor.getDevice_id(),deviceList));
                monitorExport.setDevice_ip(getDeviceIP(monitor.getDevice_id(),deviceList));
                monitorExport.setDevice_model(getDeviceModel(monitor.getDevice_id(),deviceList));
                monitorExport.setSensor_name(getSensorName(monitor.getSensor_id(),sensorList));
                monitorExport.setMonitor_name(monitor.getName());
                monitorExport.setMonitor_code(monitor.getDescription());
                monitorExportList.add(monitorExport);
            }

            HSSFWorkbook book = new HSSFWorkbook();
            HSSFSheet sheet = book.createSheet();
            String[] columns = {"区域","建筑物","楼层","报警主机","主机IP","主机备注","传感器类别","监测点名称","监测点回路号"};
            HSSFRow headRow = sheet.createRow(0);
            for(int i = 0; i < columns.length; i++){
                HSSFCell cell = headRow.createCell(i);
                cell.setCellValue(columns[i]);
                sheet.setColumnWidth(i,38*150);
            }
            for(int i = 1; i < monitorExportList.size() +1; i++){
                MonitorExport a = monitorExportList.get(i-1);
                HSSFRow nextRow = sheet.createRow(i);
                HSSFCell cell = nextRow.createCell(0);
                cell.setCellValue(a.getArea());
                cell = nextRow.createCell(1);
                cell.setCellValue(a.getBuilding());
                cell = nextRow.createCell(2);
                cell.setCellValue(a.getFloor());
                cell = nextRow.createCell(3);
                cell.setCellValue(a.getDevice_name());
                cell = nextRow.createCell(4);
                cell.setCellValue(a.getDevice_ip());
                cell = nextRow.createCell(5);
                cell.setCellValue(a.getDevice_model());
                cell = nextRow.createCell(6);
                cell.setCellValue(a.getSensor_name());
                cell = nextRow.createCell(7);
                cell.setCellValue(a.getMonitor_name());
                cell = nextRow.createCell(8);
                cell.setCellValue(a.getMonitor_code());
            }
            String fileName = "监测点信息.xls";
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            book.write(os);
            byte[] content = os.toByteArray();
            InputStream is = new ByteArrayInputStream(content);
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName).getBytes(), "iso-8859-1"));
            ServletOutputStream out = response.getOutputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(out);
            byte[] buff = new byte[4096];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bis.close();
            bos.close();

            return MapRet.FILE_DOWNLOAD_SUCCESS();
        }catch (Exception e){
            e.printStackTrace();
            logger.error("监测点导出错误：" + e);
            return MapRet.FILE_DOWNLOAD_ERROR();
        }
    }


/*    ############################################################################*/
    public String getGeobuildingName(int geoID,List<GeoBuilding> geoBuildings){
        for(GeoBuilding geoBuilding : geoBuildings){
            if(geoBuilding.getId() == geoID){
                return geoBuilding.getName();
            }
        }
        return null;
    }

    public String getDeviceName(int deviceID,List<Device> devices){
        for(Device device : devices){
            if(device.getId() == deviceID) return device.getName();
        }
        return null;
    }

    public String getDeviceIP(int deviceID,List<Device> devices){
        for(Device device : devices){
            if(device.getId() == deviceID) return IPConver.int2Ip(device.getIp());
        }
        return null;
    }

    public String getDeviceModel(int deviceID,List<Device> devices){
        for(Device device : devices){
            if(device.getId() == deviceID) return device.getDescription();
        }
        return null;
    }

    public String getSensorName(int sensorID, List<Sensor> sensorList){
        for(Sensor sensor : sensorList){
            if(sensor.getId() == sensorID)
                return sensor.getName();
        }
        return null;
    }

}
